package com.sea.base.json.typeAdapter

import com.google.gson.TypeAdapter
import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter

class DefIntegerTypeAdapter : TypeAdapter<Int>() {
    private val typeName = "int"
    override fun write(out: JsonWriter, value: Int?) {
        out.value(value)
    }

    /**
     * 返回null：泛型是int则为默认值
     * 以前默认处理：泛型是Integer则修改为null（默认值被覆盖），见[ReflectiveTypeAdapterFactory.createBoundField]#read
     * 优化后：如果为null将保留原始默认值，见[MyReflectiveTypeAdapterFactory.createBoundField]#read
     */
    override fun read(inReader: JsonReader?): Int? {
        return readNumber(inReader, typeName, { it.toInt() }, { it.asInt })
    }
}